package com.qgzj.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.qgzj.entity.Content;
import com.qgzj.service.ContentService;
import com.qgzj.service.OcrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ScheduleTask {
    public static String BaiDu_over_time_code = "17";
    public static String BaiDu_Success_code = "0";
    @Autowired
    ContentService contentService;
    @Autowired
    OcrService ocrService;

    @Scheduled(cron = "0 */20 * * * ?")
    public void timerRun() {
        AipOcr ocrClient = ocrService.getOcrClient();
        List<Content> contents = contentService.getPicUrlFromContent();
        for (Content content : contents) {
            if (StringUtils.isNotBlank(content.getPicUrl()) && content.getStatus() == 0) {
                String picUrl = content.getPicUrl();
                String res = ocrService.bdCommonOcr(ocrClient, picUrl);
                log.info("调用百度识别，contentId: {} ,url: {} ,识别结果: {}", content.getId(), content.getPicUrl(), res);
                //res结果处理
                String text = ocrService.processText(res);
                JSONObject jsonObject = JSON.parseObject(text);
                String code = jsonObject.getString("code");
                if (BaiDu_over_time_code.equals(code)) {
                    log.info("OCR识别次数使用完了！！！！！");
                    break;
                }
                if (!BaiDu_Success_code.equals(code)) {
                    log.info("OCR识别出现错误 {}", jsonObject.getString("text"));
                    continue;
                }
                String contentText = jsonObject.getString("text");
                log.info("识别的图片结果--contentNo {}  picUrl {}  text " + "\r\n" + " {}"
                        , content.getContentNo(), content.getPicUrl(), contentText);
                contentService.updateContentText(content.getId(), contentText);
            }
        }
    }
}
